# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(plyr)
library(gridExtra)
library(scales)
library(egg)
library(VennDiagram)
library(optparse)
library(tidyverse)
library(magrittr)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
  set_colnames(c("arg", "value")) %>%
  column_to_rownames("arg")

svmTop <- configData["svmTop", "value"] %>%
  as.numeric()
rfTop <- configData["rfTop", "value"] %>%
  as.numeric()

parent <- paste0("./")
createWhenNoExist(parent)
rfFileName <- str_c("01/RF_Top", rfTop, "_Imp_Rank.csv")

if (!file.exists(rfFileName)) {
  quit(status = 0)
}

rfData <- read_csv(rfFileName) %>%
  rename(`Random Forest` = Metabolite) %>%
  mutate(id = 1:n()) %>%
  select(c("id", "Random Forest"))
svmFileName <- str_c("02/SVM_Top", svmTop, "_Imp_Rank.csv")
svmData <- read_csv(svmFileName) %>%
  rename(`SVM` = Metabolite) %>%
  mutate(id = 1:n()) %>%
  select(c("id", "SVM"))

borutaFileName <- str_c("03/Decision_Info.csv")
borutaData <- read_csv(borutaFileName) %>%
  rename(`Boruta` = X1) %>%
  filter(decision == "Confirmed")

if (nrow(borutaData) > 0) {
  borutaData <- borutaData %>%
    mutate(id = 1:n())
}else {
  borutaData <- borutaData %>%
    add_column(id = NA)
}

borutaData <- borutaData %>%
  select(c("id", "Boruta"))
outData <- rfData %>%
  full_join(svmData, by = "id") %>%
  full_join(borutaData, by = "id")

columnNames <- c("Random Forest", "SVM", "Boruta")
interName <- str_c(columnNames, collapse = " & ")
outData <- outData %>%
  mutate(!!interName := {
    values <- columnNames %>%
      map(function(t) {
        get(t)
      })
    x <- Reduce(intersect, values)
    x[1:n()]
  })

cn <- combn(columnNames, 2)
for (i in 1:ncol(cn)) {
  row <- cn[, i]
  columnName1 <- row[1]
  columnName2 <- row[2]
  columnName <- str_c(columnName1, " & ", columnName2)
  outData <- outData %>%
    mutate(!!columnName := {
      x <- intersect(get(columnName1), get(columnName2))
      x[1:n()]
    })
}

if (length(columnNames) < 5) {
  for (name in columnNames) {
    newName <- str_c(name, " only")
    outData <- outData %>%
      mutate(!!newName := {
        otherNames <- columnNames %>%
          discard(~.x %in% c(name))
        values <- c(name, otherNames) %>%
          map(function(t) {
            get(t)
          })
        x <- Reduce(setdiff, values)
        x[1:n()]
      })
  }
}

outData <- outData %>%
  mutate_all(function(x) {
    replace_na(x, "")
  }) %>%
  select(-c(1:4))
outData
write_csv(outData, "Venn_Data.csv")





